package com.glory.huaweipda.adapter

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.glory.huaweipda.R
import com.glory.huaweipda.bean.DialogLotBean

/**
 * FileName: DialogAdapter
 * Author: XJH
 * Date: 2021/7/27 10:59
 * Description:
 * History:
 */
class DialogAdapter(data: MutableList<DialogLotBean>?) :
    BaseQuickAdapter<DialogLotBean, BaseViewHolder>(R.layout.adapter_dialog, data) {

    override fun convert(holder: BaseViewHolder, item: DialogLotBean) {
        holder.setText(R.id.etContent, item.Lot)
        setEditListener(holder.getView(R.id.etContent), item,holder.adapterPosition)
        val etContent = holder.getView<EditText>(R.id.etContent)
        if (holder.adapterPosition == data.size-1&&data.size > 1){
            etContent.requestFocus()
        }else{
            etContent.clearFocus()
        }

    }

    private fun setEditListener(editText: EditText, item: DialogLotBean,position:Int) {
        if (editText.tag is TextWatcher) {
            editText.removeTextChangedListener(editText.tag as TextWatcher)
        }
        val watcher: TextWatcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                item.Lot = s.toString()
                val toString = s.toString()
                if (toString.indexOf("\r") >= 0 || toString.indexOf("\n") >= 0) {
                    editText.setText(toString.replace("\r", "").replace("\n", ""));
                    if(position == data.size-1&&data.size >= 1){
                        addData(DialogLotBean())
                    }else{
                    notifyItemChanged(data.size-1)
                    }
                }
            }
        }
        editText.addTextChangedListener(watcher)
        editText.tag = watcher
    }
}